 <?php
date_default_timezone_set('Europe/Paris');

 
define("__WIDGETPATH__", 'widgets/');
define("__MODELFILE__", 'model.php');
define("__VIEWFILE__", 'view.php');


class Widget
{
	protected $_name; //Nom du widget

	protected $_page; // Page dans laquelle sera affiché le widget
	protected $_var; // Variable qui contiendra le contenu html du widget

	protected $_cache; //Cache du widget

	private $_content = array(); //Contenu du widget

	function __construct($name, $page, $var=null)
	{
		$this->_name= $name;
		$this->_var=$var;
	
		$this->_conf['CacheExpire']= 0; //Expiration du cache en secondes. 
		$this->_conf['CacheUrl']=__CACHEPATH__.'_'.$page.'_'.$name.__CACHEEXT__;
	}

	//Si le cache est expiré
	private function isCacheExpired()
	{
		if(!file_exists($this->_conf['CacheUrl']))
			return true;
		else
			return ((time() - filemtime($this->_conf['CacheUrl'])) > ($this->_conf['CacheExpire']));
	}

	//
	public function assign( $data = array() )
	{
		foreach( $data as $k=>$v )
			$this->_content[$k]=$v;
	}

	public function getVar()
	{
		return $this->_var;
	}

	//Retourne le code html (sans traduction)
	public function getHTML()
	{
		//Si le fichier est déjà enregistré on l'affiche
		if($this->_conf['CacheExpire'] > 30 && !$this->isCacheExpired())
			return file_get_contents($this->_conf['CacheUrl']);

		//Sinon

		extract($this->_content);

		ob_start(); //On démarre la cache

		echo '<!-- Genereration: '.date('d/m/Y H:i:s').'  -- Widget: '.$this->_name.' -->';
		include __WIDGETPATH__.'/'.$this->_name.'/'.__MODELFILE__;
		include __WIDGETPATH__.'/'.$this->_name.'/'.__VIEWFILE__;
		$result = ob_get_contents();

		ob_end_clean();

		//On enregistre le résulat dans un cache
		if($this->_conf['CacheExpire'] > 30 && $this->isCacheExpired() )
			file_put_contents($this->_conf['CacheUrl'], $result);

		return $result;
	}
}